<?php
/**
 * Action Helper for loading forms
 * 
 * @uses Zend_Controller_Action_Helper_Abstract
 * 
 * We'll assume that form classes are stored in the 'forms' subdirectory of the current module. 
 * We'll also assume that they are namespaced with the current module (unless we're in the default module), 
 * plus the prefix 'Form_'; e.g., if we had a 'news' module, forms would be prefixed with 'News_Form_'. 
 * Finally we'll use the name passed to the helper to determine which form class to load, using the prefix. 
 * We'll primarily use the direct() method to interact with the helper, as we only really have one thing 
 * we want the helper to do -- load forms. 
 *   
*/

class My_Controller_Action_Helper_FormLoader extends Zend_Controller_Action_Helper_Abstract
{
    /**
     * @var Zend_Loader_PluginLoader
     */
    public $pluginLoader;

    /**
     * Constructor: initialize plugin loader
     * 
     * @return void
     */
    public function __construct()
    {
        $this->pluginLoader = new Zend_Loader_PluginLoader();
    }

    /**
     * Load a form with the provided options
     * 
     * @param  string $name 
     * @param  array|Zend_Config $options 
     * @return Zend_Form
     */
    public function loadForm($name, $options = null)
    {
        $module  = $this->getRequest()->getModuleName();
        $front   = $this->getFrontController();
        $default = $front->getDispatcher()
                         ->getDefaultModule();
        if (empty($module)) {
            $module = $default;
        }
        $moduleDirectory = $front->getControllerDirectory($module);
        $formsDirectory  = dirname($moduleDirectory) . '/forms';

        $prefix = (('default' == $module) ? '' : ucfirst($module) . '_')
                . 'Form_';
        $this->pluginLoader->addPrefixPath($prefix, $formsDirectory);

        $name      = ucfirst((string) $name);
        $formClass = $this->pluginLoader->load($name);
        return new $formClass($options);
    }

    /**
     * Strategy pattern: call helper as broker method
     * 
     * @param  string $name 
     * @param  array|Zend_Config $options 
     * @return Zend_Form
     */
    public function direct($name, $options = null)
    {
        return $this->loadForm($name, $options);
    }
}